<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="catelogId">
        <el-cascader
          placeholder="请选择所属分类"
          v-model="queryParams.catelogPath"
          :options="categoryList"
          :props="cateprops"
          @keyup.enter.native="handleQuery"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="基准重量" prop="weight">
        <el-input
          v-model="queryParams.weight"
          placeholder="请输入基准重量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cloudmallproduct:spuInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cloudmallproduct:spuInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cloudmallproduct:spuInfo:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['cloudmallproduct:spuInfo:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="2" style="text-align: right">
        <!-- 切换分类显示方式的按钮 -->
        <el-button type="primary" size="mini" @click="toggleCategoryDisplay">
          {{ showFullPath ? "显示末级分类" : "显示完整路径" }}
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="spuInfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center">
        <template #default="{ $index }">
          {{
            queryParams.pageNum * queryParams.pageSize -
            queryParams.pageSize +
            $index +
            1
          }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="spuName" />
      <el-table-column label="商品描述" align="center" prop="spuDescription" />
      <el-table-column label="所属分类" align="center" prop="catelogId">
        <template #default="{ row }">
          {{ showFullPath ? getCategoryFullPath(row) : getCategoryName(row) }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brandName">
      </el-table-column>
      <el-table-column label="基准重量" align="center" prop="weight" />
      <el-table-column label="上架状态" align="center" prop="publishStatus">
        <template #default="{ row }">
          <el-tag v-if="row.publishStatus === 0" type="danger">下架</el-tag>
          <el-tag v-else type="primary">上架</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-aim"
            @click="selectBaseAttr(scope.row)"
            v-hasPermi="['cloudmallproduct:spuInfo:remove']"
            >规格</el-button
          >
          <!-- 新增：动态上架/下架按钮 -->
          <el-button
            size="mini"
            type="text"
            :icon="
              scope.row.publishStatus === 0
                ? 'el-icon-upload2'
                : 'el-icon-download'
            "
            :style="{
              color: scope.row.publishStatus === 0 ? '#13ce66' : '#ff4949',
            }"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['cloudmallproduct:spuInfo:edit']"
          >
            {{ scope.row.publishStatus === 0 ? "上架" : "下架" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改spu信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="spuName">
          <el-input v-model="form.spuName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述" prop="spuDescription">
          <el-input
            v-model="form.spuDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="是否上架">
          <el-switch
            v-model="form.publishStatus"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
        <el-form-item label="所属分类" prop="catelogId">
          <el-cascader
            placeholder="请选择所属分类"
            v-model="form.catelogPath"
            :options="categoryList"
            :props="cateprops"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="品牌" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="基准重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入基准重量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSpuInfo,
  getSpuInfo,
  delSpuInfo,
  addSpuInfo,
  updateSpuInfo,
  changeSpuStatus
} from "@/api/product/spuInfo";
import { listWithTree } from "@/api/product/category";

export default {
  name: "SpuInfo",
  data() {
    return {
      // 当前分类完成路径
      catelogPath: [],
      // 所有分类
      categoryList: [],
      cateprops: {
        value: "catId",
        label: "name",
        children: "children",
      },
      // 控制分类显示方式：true显示完整路径，false显示末级名称
      showFullPath: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // spu信息表格数据
      spuInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spuName: null,
        spuDescription: null,
        catelogId: null,
        brandName: null,
        weight: null,
        publishStatus: null,
      },
      // 表单参数
      form: {
        publishStatus: 0,
      },
      // 表单校验
      rules: {},
    };
  },
  created() {
    // 先获取分类树，再获取表格数据
    this.getCateGoryList()
      .then(() => {
        this.getList();
      })
      .catch((error) => {
        console.error("分类树加载失败，仍尝试获取表格数据：", error);
        this.getList();
      });
  },
  methods: {
    // 查询商品规格参数信息
    selectBaseAttr(){

    },
    // 商品上下架
    handleChangeStatus(spu) {
      // 1. 确定目标状态和提示文本
      const targetStatus = spu.publishStatus === 0 ? 1 : 0;
      const statusText = targetStatus === 1 ? "上架" : "下架";

      // 2. 弹窗确认操作（避免误触）
      this.$modal
        .confirm(`是否确认将商品「${spu.spuName}」${statusText}？`)
        .then(() => {
          // 3. 调用接口：传递商品ID和目标状态
          return changeSpuStatus({
            id: spu.id, // 商品ID
            publishStatus: targetStatus, // 目标状态（1=上架，0=下架）
          });
        })
        .then((response) => {
          // 4. 接口成功：提示+刷新列表
          this.$modal.msgSuccess(`商品${statusText}成功`);
          this.getList(); // 刷新列表，实时更新状态
        })
        .catch(() => {
          // 5. 接口失败/用户取消：不做操作
        });
    },
    // 切换表格行分类显示方式
    toggleCategoryDisplay() {
      this.showFullPath = !this.showFullPath;
    },
    // 根据分类ID获取末级分类名称
    getCategoryName(data) {
      let catelogId = data.catelogId;
      if (!catelogId) return "未知分类";
      const findNode = (tree, id) => {
        for (const node of tree) {
          if (String(node.catId) === String(id)) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findNode(node.children, id);
            if (found) return found;
          }
        }
        return null;
      };

      const node = findNode(this.categoryList, catelogId);
      return node ? node.name : "未知分类";
    },

    // 根据分类ID获取完整分类路径
    getCategoryFullPath(data) {
      let catelogId = data.catelogId;
      if (!catelogId) return "未知分类";

      const path = [];
      const findPath = (tree, id) => {
        for (const node of tree) {
          path.push(node.name);
          if (node.catId === id) {
            return true;
          }
          if (node.children && node.children.length > 0) {
            if (findPath(node.children, id)) {
              return true;
            }
          }
          path.pop();
        }
        return false;
      };

      const found = findPath(this.categoryList, catelogId);
      return found ? path.join("/") : "未知分类";
    },
    /** 查询spu信息列表 */
    getList() {
      this.loading = true;
      listSpuInfo(this.queryParams).then((response) => {
        this.spuInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取所有商品分类
    getCateGoryList() {
      return new Promise((resolve, reject) => {
        listWithTree()
          .then((response) => {
            let rawData = response.rows || [];
            this.categoryList = this.filterTreeByShowStatus(rawData);
            resolve();
          })
          .catch((error) => {
            console.error("获取分类列表失败：", error);
            this.categoryList = [];
            reject(error);
          });
      });
    },
    // 递归过滤树形数据：移除showStatus=0的节点
    filterTreeByShowStatus(tree) {
      return tree
        .filter((node) => node.showStatus === 1) // 只保留showStatus=1的节点
        .map((node) => {
          // 对每个节点的children也进行递归过滤
          if (node.children && node.children.length > 0) {
            node.children = this.filterTreeByShowStatus(node.children);
          }
          return node;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        spuName: null,
        spuDescription: null,
        catalogId: null,
        brandId: null,
        weight: null,
        publishStatus: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (
        this.queryParams.catelogPath &&
        this.queryParams.catelogPath.length > 0
      ) {
        this.queryParams.catelogId =
          this.queryParams.catelogPath[this.queryParams.catelogPath.length - 1];
      } else {
        this.queryParams.catelogId = null; // 空值时，将 catelogId 置为 null（后端通常识别 null 为“不筛选”）
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加spu信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSpuInfo(id).then((response) => {
        this.form = response.data;
        // 回显分类路径
        this.setCategoryPath(response.data.catelogId);
        this.open = true;
        this.title = "修改spu信息";
      });
    },
    // 根据分类ID设置分类路径（用于修改时回显）
    setCategoryPath(catelogId) {
      if (!catelogId) return;

      const path = [];
      const findPath = (tree, id) => {
        for (const node of tree) {
          path.push(node.catId);
          if (node.catId === id) {
            return true;
          }
          if (node.children && node.children.length > 0) {
            if (findPath(node.children, id)) {
              return true;
            }
          }
          path.pop();
        }
        return false;
      };

      findPath(this.categoryList, catelogId);
      this.form.catelogPath = path;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        // 分类id赋值
        if (this.form.catelogPath && this.form.catelogPath.length > 0) {
          this.form.catelogId =
            this.form.catelogPath[this.form.catelogPath.length - 1];
        } else {
          this.$message.error("请选择所属分类");
          return;
        }
        if (valid) {
          if (this.form.id != null) {
            updateSpuInfo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpuInfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除spu信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSpuInfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cloudmallproduct/spuInfo/export",
        {
          ...this.queryParams,
        },
        `spuInfo_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
